package com.zatech.cgnci.project.controller.statement;


import cn.hutool.core.io.IoUtil;
import com.zatech.cgnci.project.base.enums.ResponseCodeEnum;
import com.zatech.cgnci.project.base.exception.GlobalException;
import com.zatech.cgnci.project.service.CngciStatementPdfService;
import com.zatech.cgnci.project.vo.DownloadFileVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/api/pdf-download")
@Api(produces = "application/json", tags = "账单管理PDF文档下载接口")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
public class PdfController {

    private final CngciStatementPdfService pdfService;
//    @GetMapping(value = "/generate-pdf")
//    @ApiOperation(value = "生成PDF", produces = "application/octet-stream")
//    public void generatePdf(Long id,String billType) {
//        pdfService.generatePdf(id,billType);
//    }

    @GetMapping("/generate-pdf")
    @ApiOperation(value = "生成PDF")
    public void downloadFile(HttpServletResponse response,@RequestParam Long id,@RequestParam String billType) {
        try {
            DownloadFileVO fileVO = pdfService.generatePdf(id,billType); // 获取文件内容
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileVO.getPdfName(), "UTF-8"));
            response.setContentType(MediaType.APPLICATION_PDF_VALUE);
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            IoUtil.write(response.getOutputStream(), true, fileVO.getContent());
            response.getOutputStream().flush();
        }catch (IOException e){
            throw new GlobalException(ResponseCodeEnum.PARAMS_ILLEGAL, "下载文件失败"+e.getMessage());
        }
    }
}
